package com.example.demo.leetcode.classics150;

import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * ******************************************************
 *
 * @author liugh9
 * @version 1.0
 * @classname _94课程表II
 * @description
 * @date 2023/08/08 16:10
 * <p>
 * ******************************************************
 */
public class _94课程表II {



    public int[] findOrder(int numCourses, int[][] prerequisites) {
        List<Integer>[] graph = new List[numCourses];
        for (int i = 0; i < numCourses; i++) {
            graph[i] = new LinkedList<>();
        }
        int[] inDegree = new int[numCourses];

        for (int[] prerequisite : prerequisites) {
            int from = prerequisite[1];
            int to = prerequisite[0];
            inDegree[to]++;
            graph[from].add(to);
        }

        // 根据入度初始化队列中的节点
        Queue<Integer> q = new LinkedList<>();
        for (int i = 0; i < inDegree.length; i++) {
            if (inDegree[i] == 0) {
                q.offer(i);
            }
        }
        int[] res = new int[numCourses];
        int count = 0;
        while (!q.isEmpty()) {
            Integer curr = q.poll();
            res[count] = curr;
            count++;
            for (Integer item : graph[curr]) {
                inDegree[item]--;
                if (inDegree[item] == 0) {
                    q.offer(item);
                }
            }
        }

        if (count != numCourses) {
            return new int[]{};
        }
        return res;
    }

}
